<?php

namespace Admin\Controller;


use Think\Page;

class GoodsOrderController extends AdminController {

    public function index() {
        $order_id = I('order_id', '', 'addslashes,trim');
        $nickname = I('nickname', '', 'addslashes,trim');
        $order_status = I('order_status', '', 'intval');
        $where = [];

        if (!empty($order_id)) {
            $where['A.order_id'] = $order_id;
        }

        if (!empty($nickname)) {
            $where['B.nickname'] = $nickname;
        }
        if (!empty($order_status)) {
            $where['A.order_status'] = $order_status;
        }

        $count = M('GoodsOrder')->alias('A')->field('A.id')
            ->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')
            ->where($where)->count();
        $Page = new Page($count, $this->page_size);
        $result = M('GoodsOrder')->alias('A')->field('A.*,B.nickname')
            ->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')
            ->where($where)->order('id DESC')->limit($Page->firstRow, $this->page_size)->select();

        $this->assign([
            'result' => $result,
            'page' => $Page->show(),
        ]);
        $this->display();
    }

    //待续
    public function detail() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $order = M('GoodsOrder')->alias('A')->field('A.*,B.nickname')
            ->join(C('DB_PREFIX') . 'user as B ON A.user_id = B.id', 'left')
            ->where(['A.id' => $id])->find();
        if (empty($order)) {
            return $this->error('没有找到订单');
        }
        $order['goods'] = M('GoodsOrderDetail')->where(['order_id' => $order['order_id']])->select();

        $this->assign([
            'order' => $order,
        ]);
        $this->display();
    }

    //确认发货
    public function send_package() {
        $id = I('id', 0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $order = M('GoodsOrder')->where(['id' => $id])->find();
        if (empty($order)) {
            return $this->error('没有找到订单');
        }
        if ($order['order_status'] != 1) {
            return $this->error('该订单暂时不能设置发货');
        }
        if (IS_POST) {
            $express_code = I('express_code', '', 'addslashes,trim');
            if (empty($express_code)) {
                return $this->error('请输入快递单号');
            }

            M('GoodsOrder')->where(['id' => $order['id']])->save([
                'order_status' => 2,
                'express_code' => $express_code,
                'express_at' => time(),
            ]);
            return $this->success('订单状态更改成功');

        } else {
            $this->assign('order', $order);
            return $this->display();
        }
    }
}